
<template>
  <div class="manage-container">
    <!-- 待发货订单模块 -->
    <el-card class="module-card shipping-card">
      <template #header>
        <div class="card-header">
          <span class="title">🛒 待处理订单</span>
          <el-tag type="warning">待发货 {{ pendingOrders.length }} 笔</el-tag>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loadingOrders">
        <el-col 
          v-for="order in pendingOrders" 
          :key="order.orderId" 
          :xs="24" :sm="12" :md="8" :lg="6"
        >
          <div class="order-item">
            <div class="product-image">
              <img :src="formatImage(order.images)" alt="商品图片" />
            </div>
            <div class="order-info">
              <h3 class="product-name">{{ order.productName }}</h3>
              <div class="meta-info">
                <span>订单号: {{ order.orderNumber }}</span>
                <el-tag size="mini" effect="dark">买家: {{ order.nickname }}</el-tag>
              </div>
              <div class="amount-info">
                <span class="price">¥{{ order.price }}</span>
                <span class="quantity">x{{ order.quantity }}</span>
              </div>
              <div class="actions">
                <el-button 
                  type="success" 
                  size="small"
                  @click="handleShip(order)"
                >
                  🚚 立即发货
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
        <el-empty v-if="!pendingOrders.length" description="暂无待发货订单" />
      </el-row>
    </el-card>

    <!-- 售后处理模块 -->
    <el-card class="module-card after-sales-card">
      <template #header>
        <div class="card-header">
          <span class="title">🔄 售后处理</span>
          <el-tag type="warning">待处理 {{ afterSalesList.length }} 笔</el-tag>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loadingAfterSales">
        <el-col 
          v-for="order in afterSalesList" 
          :key="order.orderId" 
          :xs="24" :sm="12" :md="8" :lg="6"
        >
          <div class="order-item">
            <div class="product-image">
              <img :src="formatImage(order.images)" alt="商品图片" />
            </div>
            <div class="order-info">
              <h3 class="product-name">{{ order.productName }}</h3>
              <div class="meta-info">
                <span>订单号: {{ order.orderNumber }}</span>
                <el-tag size="mini" effect="dark">
                  {{ order.afterSalesType === 1 ? '仅退款' : '退货退款' }}
                </el-tag>
              </div>
              <div class="amount-info">
                <span class="price">¥{{ order.totalAmount }}</span>
                <span class="quantity">x{{ order.quantity }}</span>
              </div>
              <div class="reason">
                <el-tooltip effect="light" :content="order.reason" placement="top">
                  <span class="reason-text">{{ truncateReason(order.reason) }}</span>
                </el-tooltip>
              </div>
              <div class="actions">
                <el-button 
                  type="success" 
                  size="small"
                  @click="handleApprove(order.orderId)"
                >
                  ✓ 通过
                </el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  @click="showRejectDialog(order.orderId)"
                >
                  ✗ 拒绝
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
        <el-empty v-if="!afterSalesList.length" description="暂无待处理售后" />
      </el-row>
    </el-card>

    <!-- 已发布商品模块 -->
    <el-card class="module-card product-card">
      <template #header>
        <div class="card-header">
          <span class="title">📦 我的商品</span>
          <el-button type="primary" size="small" @click="navigateToPublish">
            ➕ 发布新商品
          </el-button>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loadingProducts">
        <el-col 
          v-for="product in myProducts" 
          :key="product.productId" 
          :xs="24" :sm="12" :md="8" :lg="6"
        >
          <div class="product-item">
            <div class="image-wrapper">
              <img :src="formatImage(product.images)" alt="商品图片" />
              <div class="status-tag">
                <el-tag 
                  :type="product.productState === 1 ? 'success' : 'info'" 
                  effect="dark"
                >
                  {{ product.productState === 1 ? '已售出' : '出售中' }}
                </el-tag>
              </div>
            </div>
            <div class="product-content">
              <h3 class="title">{{ product.productName }}</h3>
              <div class="stats">
                <div class="stat-item">
                  <el-icon><Money /></el-icon>
                  <span>¥{{ product.price }}</span>
                </div>
                <div class="stat-item">
                  <el-icon><Box /></el-icon>
                  <span>{{ product.count }} 件</span>
                </div>
                <div class="stat-item">
                  <el-icon><View /></el-icon>
                  <span>{{ product.click }} 次</span>
                </div>
              </div>
              <div class="actions">
                <el-button type="primary" size="small" @click="navigateToEdit(product.productId)">📝 编辑</el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  :loading="deletingProductId === product.productId"
                  @click="handleDeleteProduct(product.productId)"
                >
                  🗑️ {{ deletingProductId === product.productId ? '下架中' : '下架' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
        <el-empty v-if="!myProducts.length" description="暂未发布商品" />
      </el-row>
    </el-card>

    <!-- 拒绝原因弹窗 -->
    <el-dialog v-model="rejectVisible" title="填写拒绝原因" width="500px">
      <el-input
        v-model="rejectReason"
        type="textarea"
        :rows="4"
        placeholder="请输入详细的拒绝理由（至少20个字符）"
        show-word-limit
        maxlength="200"
      />
      <template #footer>
        <el-button @click="rejectVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          :disabled="rejectReason.length < 20"
          @click="handleReject"
        >
          提交拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute , useRouter} from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Money, Box, View } from '@element-plus/icons-vue'

const route = useRoute()
const userId = ref(parseInt(route.query.userId))
const deletingProductId = ref(null)
// 数据状态
const pendingOrders = ref([])
const myProducts = ref([])
const afterSalesList = ref([])
const loadingOrders = ref(true)
const loadingProducts = ref(true)
const loadingAfterSales = ref(false)
const rejectVisible = ref(false)
const rejectReason = ref('')
const currentOrderId = ref(null)
const router= useRouter()
// 图片处理
const formatImage = (images) => {
  return images ? `http://localhost:8092${images.split(',')[0]}` : '/default-product.jpg'
}

// 缩短原因显示
const truncateReason = (text) => {
  return text?.length > 30 ? text.substring(0, 30) + '...' : text
}
//编辑商品
const navigateToEdit = (productId) => {
  const routeData = router.resolve({
    path:'/edit',
    query: { productId }
  })
 window.open(routeData.href, '_blank')
}
// 下架商品处理
const handleDeleteProduct = async (productId) => {
  try {
    // 确认弹窗
    await ElMessageBox.confirm(
      '确定要下架该商品吗？下架后不可恢复！',
      '危险操作确认',
      {
        confirmButtonText: '确认下架',
        cancelButtonText: '取消',
        type: 'error',
        center: true,
        customClass: 'danger-confirm-box'
      }
    )
    
    deletingProductId.value = productId
    
    const token = localStorage.getItem('token')
    const { data } = await axios.delete('http://localhost:8092/product/delete', {
      params: { productId },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    if (data.code === 200) {
      ElMessage.success({
        message: '商品下架成功',
        duration: 2000,
        customClass: 'success-message'
      })
      // 从本地数据中移除
      myProducts.value = myProducts.value.filter(p => p.productId !== productId)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error({
        message: `下架失败: ${error.response?.data?.msg || error.message}`,
        duration: 3000,
        customClass: 'error-message'
      })
    }
  } finally {
    deletingProductId.value = null
  }
}
// 获取待发货订单
const fetchPendingOrders = async () => {
  try {
    const { data } = await axios.get('http://localhost:8092/order/getOrderBySellerId', {
      params: { sellerId: userId.value }
    })
    pendingOrders.value = data.data.filter(o => o.status === 2)
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loadingOrders.value = false
  }
}

// 获取已发布商品
const fetchMyProducts = async () => {
  try {
    const { data } = await axios.get('http://localhost:8092/product/getProductsByUserId', {
      params: { userId: userId.value }
    })
    myProducts.value = data.data
  } catch (error) {
    ElMessage.error('获取商品失败')
  } finally {
    loadingProducts.value = false
  }
}
const navigateToPublish = () => {
  const router= useRouter()
}
// 获取待处理售后
const fetchAfterSales = async () => {
  try {
    loadingAfterSales.value = true
    const { data } = await axios.get('http://localhost:8092/order/pendingAfterSales', {
      params: { sellerId: userId.value }
    })
    afterSalesList.value = data.data || []
  } catch (error) {
    ElMessage.error('获取售后数据失败')
  } finally {
    loadingAfterSales.value = false
  }
}

// 发货操作
const handleShip = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认要发货订单 ${order.orderNumber} 吗？`,
      '发货确认',
      {
        confirmButtonText: '确认发货',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    )

    const { data } = await axios.put('http://localhost:8092/order/confirmShipment', null, {
      params: { orderId: order.orderId }
    })

    if (data.code === 200) {
      ElMessage.success({ message: '发货成功!', duration: 3000 })
      await fetchPendingOrders()
    } else {
      ElMessage.error(data.msg || '发货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '发货操作失败')
    }
  }
}

// 通过售后申请
const handleApprove = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定通过该售后申请吗？', '确认操作', {
      confirmButtonText: '确定通过',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const { data } = await axios.put(
      'http://localhost:8092/order/processAfterSales',
      null,
      { params: { orderId, approve: true } }
    )
    
    if (data.code === 200) {
      ElMessage.success('处理成功')
      fetchAfterSales()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '操作失败')
    }
  }
}

// 显示拒绝弹窗
const showRejectDialog = (orderId) => {
  currentOrderId.value = orderId
  rejectVisible.value = true
}

// 提交拒绝
const handleReject = async () => {
  try {
    const { data } = await axios.put(
      'http://localhost:8092/order/processAfterSales',
      null,
      { 
        params: { 
          orderId: currentOrderId.value,
          approve: false,
          rejectReason: rejectReason.value 
        }
      }
    )
    
    if (data.code === 200) {
      ElMessage.success('已拒绝申请')
      rejectVisible.value = false
      rejectReason.value = ''
      fetchAfterSales()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 初始化加载
onMounted(() => {
  fetchPendingOrders()
  fetchMyProducts()
  fetchAfterSales()
})
</script>
  
<style lang="scss" scoped>
@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.manage-container {
  max-width: 1400px;
  margin: 2rem auto;
  padding: 0 20px;
}

.module-card {
  margin-bottom: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #f8fafc, #f1f5f9);
    border-bottom: 1px solid #e2e8f0;
    padding: 1.2rem 1.5rem;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 1.25rem;
      font-weight: 600;
      color: #1e293b;
    }
  }
}

/* 订单项通用样式 */
.order-item {
  background: white;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  transition: transform 0.2s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 100%;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .product-image {
    height: 200px;
    overflow: hidden;
    border-radius: 8px 8px 0 0;
    position: relative;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s ease;
    }

    &:hover img {
      transform: scale(1.05);
    }
  }

  .order-info {
    padding: 1rem;
    flex: 1;
    display: flex;
    flex-direction: column;

    .product-name {
      font-size: 1rem;
      margin: 0 0 0.8rem;
      color: #334155;
      @include text-ellipsis;
      line-height: 1.4;
    }

    .meta-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 0.85rem;
      color: #64748b;
      margin-bottom: 0.8rem;

      .el-tag {
        max-width: 120px;
        @include text-ellipsis;
      }
    }

    .amount-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.2rem;

      .price {
        color: #ef4444;
        font-weight: 600;
        font-size: 1.1rem;
      }

      .quantity {
        color: #64748b;
        font-size: 0.9rem;
      }
    }

    .reason {
      margin-bottom: 15px;
      
      .reason-text {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        color: #666;
        font-size: 12px;
        line-height: 1.5;
      }
    }

    .actions {
      margin-top: auto;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }
}

/* 商品项样式 */
.product-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 1.5rem;
  transition: all 0.2s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 100%;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .image-wrapper {
    height: 220px;
    overflow: hidden;
    position: relative;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s ease;
    }

    &:hover img {
      transform: scale(1.05);
    }

    .status-tag {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 1;
    }
  }

  .product-content {
    padding: 1.2rem;
    flex: 1;
    display: flex;
    flex-direction: column;

    .title {
      font-size: 1.1rem;
      font-weight: 500;
      color: #1e293b;
      margin: 0 0 1rem;
      @include text-ellipsis;
      line-height: 1.4;
    }

    .stats {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 0.8rem;
      margin-bottom: 1.2rem;

      .stat-item {
        display: flex;
        align-items: center;
        font-size: 0.9rem;
        color: #64748b;

        .el-icon {
          margin-right: 0.4rem;
          font-size: 1.1rem;
          color: #475569;
        }

        span {
          @include text-ellipsis;
        }
      }
    }

    .actions {
      margin-top: auto;
      display: flex;
      justify-content: space-between;
      gap: 0.8rem;

      .el-button {
        flex: 1;
      }
    }
  }
}

/* 售后处理特殊样式 */
.after-sales-card {
  .order-item {
    background: #fff9f0;
    
    .order-info {
      .reason {
        background-color: #fff3e0;
        padding: 8px;
        border-radius: 4px;
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-image,
  .image-wrapper {
    height: 160px !important;
  }

  .order-info,
  .product-content {
    padding: 0.8rem !important;
  }

  .stats {
    grid-template-columns: repeat(2, 1fr) !important;
  }

  :deep(.el-dialog) {
    width: 90% !important;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    
    .el-tag {
      margin-top: 8px;
    }
  }
}

/* 弹窗特殊样式 */
.reject-input {
  margin-bottom: 20px;
  
  :deep(.el-textarea__inner) {
    min-height: 100px !important;
  }
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.danger-confirm-box {
  .el-message-box__headerbtn {
    display: none;
  }
  
  .el-message-box__content {
    padding: 20px;
    text-align: center;
  }
  
  .el-message-box__btns {
    justify-content: center;
    
    .el-button--primary {
      background-color: #f56c6c;
      border-color: #f56c6c;
      
      &:hover {
        background-color: #e74c3c;
        border-color: #e74c3c;
      }
    }
  }
}

.success-message {
  background-color: #f0f9eb !important;
  border-color: #e1f3d8 !important;
  color: #67c23a !important;
}

.error-message {
  background-color: #fef0f0 !important;
  border-color: #fde2e2 !important;
  color: #f56c6c !important;
}
</style>